package com.zwf.domain.strategy.service.rule.impl;

import com.zwf.domain.strategy.model.entity.RuleActionEntity;
import com.zwf.domain.strategy.model.entity.RuleMatterEntity;
import com.zwf.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.zwf.domain.strategy.repository.IStrategyRepository;
import com.zwf.domain.strategy.service.annotation.LogicStrategy;
import com.zwf.domain.strategy.service.rule.ILogicFilter;
import com.zwf.domain.strategy.service.rule.factory.DefaultLogicFactory;
import com.zwf.types.enums.ResponseCode;
import com.zwf.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author zwf
 * @description 【抽奖前规则】黑名单用户过滤规则
 * @date 2024/7/4 14:48
 */
@Slf4j
@Component
@LogicStrategy(logicModel = DefaultLogicFactory.LogicModel.RULE_BLACKLIST)
public class RuleBlacklistLogicFilter implements ILogicFilter<RuleActionEntity.RaffleBeforeEntity> {

    @Autowired
    private IStrategyRepository repository;

    @Override
    public RuleActionEntity<RuleActionEntity.RaffleBeforeEntity> filter(RuleMatterEntity ruleMatterEntity) {
        log.info("规则过滤-黑名单 userId:{} strategyId:{} ruleModel:{}", ruleMatterEntity.getUserId(), ruleMatterEntity.getStrategyId(), ruleMatterEntity.getRuleModel());
        Long userId = ruleMatterEntity.getUserId();

        //查询策略规则模型为黑名单对应的规则值
        String ruleValue = repository.queryStrategyRuleValue(ruleMatterEntity.getStrategyId(),ruleMatterEntity.getAwardId(),ruleMatterEntity.getRuleModel());
        if(ruleValue == null){
            throw new AppException(ResponseCode.STRATEGY_RULE_VALUE_IS_NULL.getCode(),ResponseCode.STRATEGY_RULE_VALUE_IS_NULL.getInfo());
        }
        //黑名单规则的值就是奖品id，即所有黑名单用户只能获得这一个奖品id对应的奖品
        Integer awardId = Integer.valueOf(ruleValue);
        Integer isBlacklist = repository.queryUserBlacklist(userId, ruleMatterEntity.getStrategyId());
        //该用户不存在于黑名单中,放行
        if(isBlacklist == 0){
            return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                    .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                    .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                    .build();
        }
        //该用户存在于黑名单中，接管
        return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                .ruleModel(DefaultLogicFactory.LogicModel.RULE_BLACKLIST.getCode())
                .data(RuleActionEntity.RaffleBeforeEntity.builder()
                        .strategyId(ruleMatterEntity.getStrategyId())
                        .awardId(awardId)
                        .build())
                .code(RuleLogicCheckTypeVO.TAKE_OVER.getCode())
                .info(RuleLogicCheckTypeVO.TAKE_OVER.getInfo())
                .build();
    }
}
